import { ref } from 'vue'

import { deptApi } from '@/apis'
import { TableRefHook, useDialog } from '@/hooks'

import { useDeptForm } from '.'

type Params = {
  tableRefHook: TableRefHook
  getDeptTree: Func
}

export function useOperation({ tableRefHook, getDeptTree }: Params) {
  const selectedId = ref('')

  const { showConfirm } = useDialog()
  const {
    show: showEdit,
    loading: editLoading,
    formModel: editFormModel,
    formRef: editFormRef
  } = useDeptForm()

  function handleShowEdit(item: any) {
    const { deptId, ...rest } = item
    selectedId.value = deptId
    editFormModel.value = rest
    showEdit.value = true
    getDeptTree()
  }

  function handleEdit() {
    editFormRef.validate().then(async () => {
      try {
        editLoading.value = true

        await deptApi.updateDept(selectedId.value, editFormModel.value)

        editLoading.value = false
        handleCloseEdit()

        await tableRefHook.refresh()
        tableRefHook.tableRef.value.setAllTreeExpand(true)
      } catch {
        editLoading.value = false
      }
    })
  }

  function handleCloseEdit() {
    showEdit.value = false
  }

  function handleDelete(id: string) {
    showConfirm({
      content: '确认删除？',
      onOk: async () => {
        await deptApi.deleteDept({
          ids: [id]
        })

        await tableRefHook.refresh()
        tableRefHook.tableRef.value.setAllTreeExpand(true)
      }
    })
  }

  return {
    showEdit,
    editLoading,
    editFormModel,
    editFormRef,
    handleShowEdit,
    handleEdit,
    handleCloseEdit,
    handleDelete
  }
}
